package com.ujoku.context;


import com.ujoku.context.constants.ExpiredCacheContext;
import com.ujoku.context.constants.SessionConstants;
import com.ujoku.domain.Cart;
import com.ujoku.domain.Member;
import com.ujoku.domain.Visitor;
import com.ujoku.service.MemberService;
import com.ujoku.service.OrderItemService;
import com.ujoku.view.builder.CartBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Greg.Chen on 2015/1/19.
 */
@Component
public class ActionContext {
    public static final String CURRENT_VISITOR = "currentVisitor";

    @Autowired(required = false)
    private HttpServletRequest request;

    @Autowired
    private MemberService memberService;

    @Autowired
    private OrderItemService orderItemService;

    @Autowired
    private CartBuilder cartBuilder;

    public HttpServletRequest getRequest() {
        return request;
    }

    /**
     * 获取当前用户
     * @return
     */
    public Member getMember() {
        HttpSession session =  request.getSession();
        Member member = (Member) session.getAttribute(SessionConstants.MEMBER);

        if(member != null && ExpiredCacheContext.expiredMemberSet.contains(member.getUser_id())){
            member = (Member) memberService.selectById(member.getUser_id());

            memberService.setLevelName(member);
            member.setUnreadCounts(memberService.getUnreadCountsById(member));

            cartBuilder.updateRelateInfo(member);

            Map<String,Object> query = new HashMap<>();
            query.put("memberId",member.getUser_id());

            int count = orderItemService.selectSalesCount(query);

            member.setSalesCount(count);

            ExpiredCacheContext.expiredMemberSet.remove(member.getUser_id());
            this.setMember(member);
        }

        return member;
    }

    public void setMember(Member member){
        HttpSession session =  request.getSession();
        memberService.setMemberPortrait(member,request);
        session.setAttribute(SessionConstants.MEMBER, member);
    }


    /**
     * 获取当前用户
     * @return
     */
    public Cart getCart() {
        HttpSession session =  request.getSession();
        return (Cart) session.getAttribute(SessionConstants.CART);
    }

    public void setCart(Cart cart){
        HttpSession session =  request.getSession();

        session.setAttribute(SessionConstants.CART, cart);
    }

    public Visitor getCurrentVisitor(){

        return (Visitor) request.getAttribute(CURRENT_VISITOR);
    }
}
